package org.xg.service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xg.dao.UserDao;
import org.xg.domain.UserVO;
import org.xg.exception.BusinessServiceException;

import com.googlecode.genericdao.search.ISearch;
import com.googlecode.genericdao.search.SearchResult;

@Service
@Transactional
public class UserBS {
	
	@PostConstruct
	public void dd(){
		System.out.println("UserBSUserBSUserBSUserBSUserBS");
	}
	
	@Resource
	private UserDao userDao ;
	
	/**
	 * 查找名为username的用户
	 * @param username
	 * @return
	 */
	public UserVO findUserByUserName(String username ){
		return userDao.findByUserName(username);
	}

	public UserVO findUserById(String id ){
		return userDao.find(id);
	}
	
	/**
	 * 按条件搜索用户
	 * @param search
	 * @return
	 */
	public SearchResult<UserVO> searchAndCount(ISearch search){
		return userDao.searchAndCount(search);
	}
	
	/**
	 * 新增or修改用户
	 * @param user
	 * @return -1：用户名重复；1：正常
	 */
	public int saveOrUpdate( UserVO user ) throws Exception{
		if( StringUtils.isBlank(user.getId()) ){
			UserVO cf = userDao.findByUserName(user.getUsername());
			if( cf == null ){
				userDao.save(user);
			}else{
				throw new BusinessServiceException("用户名不能重复！");
			}
		}else{
			UserVO oldUser = userDao.find(user.getId());
			oldUser.setPhone( user.getPhone() );
			oldUser.setEmail( user.getEmail() );
			oldUser.setUserCname( user.getUserCname() );
			oldUser.setSex( user.getSex() );
			oldUser.setValid( user.isValid() );
			userDao.saveOrUpdate(oldUser);
		}
		return 1;
	}
}
